package cn.fastoo.web.backstage.web.controller.common;

import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.service.OSSService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.net.ftp.FtpClient;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping("file")
public class FileUploadController {
	private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

	@Autowired
	private OSSService ossService;


	public static final String STATIC_PREFIEX = "http://47.96.121.149:5555/";

	public FTPClient getFtpClient(){
		try {
			int reply;
			FTPClient ftpClient = null;

			ftpClient = new FTPClient();

			//ftpClient.enterLocalPassiveMode();

			ftpClient.connect("47.96.121.149");//连接FTP服务器

			ftpClient.enterLocalPassiveMode();

			ftpClient.login("lowkey","123456q");

			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

			/*
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
			}*/

			return ftpClient;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/upload")
	@ResponseBody //resultType ==1 layUi
	public String upload(HttpServletRequest request,Integer resultType) {
		try {
			JSONObject result = new JSONObject();
			result.put("error",0);




			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("image", "gif,jpg,jpeg,png,bmp,html,htm");
			extMap.put("flash", "swf,flv");
			extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,mmap");
			String dirName = request.getParameter("dir");
			if (dirName == null) {
				dirName = "image";
			}
			if (!extMap.containsKey(dirName)) {
				return JsonResult.error("出错");
			}
			// saveUrl +=dirName+"/";
			// savePath +=dirName+"/";
			// 璁剧疆涓婁笅鏂规枃
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
					.getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						String fileName = file.getOriginalFilename();

						String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
						if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
							return JsonResult.error("错误");
						}
						String newFileName = UUID.randomUUID() + "." + fileExt;
						// File newFile = new File(savePath, newFileName);
						// FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
						FTPClient ftpClient = getFtpClient();
						try {
							boolean storeFileFlag = ftpClient.storeFile(newFileName,file.getInputStream());
							System.out.println(storeFileFlag);

						}catch (Exception e){
							e.printStackTrace();
						}finally {
							ftpClient.logout();
							ftpClient.disconnect();
						}
						//新加的
						String url = STATIC_PREFIEX+newFileName;

						JSONObject obj = new JSONObject();
						if(resultType!=null){
							if(resultType.intValue()==1){
								obj.put("src", url);
								obj.put("title", url);
								return JsonResult.success(obj);
							}else if(resultType.intValue()==2){
								JSONObject jsobject = new JSONObject();
								jsobject.put("state", "SUCCESS");
								jsobject.put("url", url);
								jsobject.put("title",newFileName);
								jsobject.put("original", newFileName);
								return jsobject.toString();
							}
						}
						obj.put("error", 0);
						obj.put("url", url);
						return obj.toString();
					}
				}
			}
		} catch (Exception e) {
			logger.error("错误", e);

		}
		return JsonResult.error("错误");
	}
	
	 



  
}
